package com.woniuxy.microsysserver.listener;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microsysserver.bean.AdminInfo;
import com.woniuxy.microsysserver.mapper.OptMapper;
import com.woniuxy.microsysserver.service.IOutService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 蜗牛学院
 * @version 1.0
 * producer_group_txmsg_bank1 名称一定要对应AccountInfoServiceImpl的 sendUpdateAccountBalance
 * 中发送的名称
 **/
@Component
@RocketMQTransactionListener(txProducerGroup = "producer_group")
public class ProducerTxmsgListener implements RocketMQLocalTransactionListener {

    @Resource
    IOutService outServiceImpl;
    @Resource
    OptMapper optMapper;
    /**
     * 事务消息发送后的回调方法，当消息发送给mq成功，此方法被回调
     */
    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

        try {
            //解析message，转成AccountChangeEvent
            String messageString = new String((byte[]) message.getPayload());
            JSONObject jsonObject = JSONObject.parseObject(messageString);
            String adminString = jsonObject.getString("admin");
            String noString = jsonObject.getString("no");
            String ip = jsonObject.getString("ip");
            //bank02 人为操作异常（导致本地事务失效）
            if(noString.equals("xxx")){
                throw new RuntimeException("人为制造异常");
            }
            //将accountChange（json）转成AccountChangeEvent
            AdminInfo admin = JSONObject.parseObject(adminString, AdminInfo.class);
            //执行本地事务，扣减金额
            outServiceImpl.addOpt(admin.getId(),noString,ip);

            //当返回RocketMQLocalTransactionState.COMMIT，自动向mq发送commit消息，mq将消息的状态改为可消费
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }


    }
    /**
     *  事务状态回查，查询是否扣减金额
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //解析message，转成AccountChangeEvent
        String messageString = new String((byte[]) message.getPayload());
        JSONObject jsonObject = JSONObject.parseObject(messageString);
        String adminString = jsonObject.getString("admin");
        String noString = jsonObject.getString("no");
        //将accountChange（json）转成AccountChangeEvent
        AdminInfo admin = JSONObject.parseObject(adminString, AdminInfo.class);
        //事务id
        String txNo = noString;
        int existTx = optMapper.isExistTx(txNo);

        if(existTx>0){
            return RocketMQLocalTransactionState.COMMIT;//如果存在，直接提交
        }else{
            return RocketMQLocalTransactionState.UNKNOWN;//如果不存在，直接删除
        }
    }
}
